import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

import 'image_preview.dart';

/// 图片之间间隔
const double itemSpace = 5.0;

/// 上下左右间隔
const double space = 0.0;

class ImageShowTool extends StatelessWidget {
  /// 原图文件列表
  final List<String>? imgData;

  /// 缩略图文件列表
  final List<String>? thumbData;

  /// 单独设置左边间距
  final double? leftSpace;

  /// 单独设置右边边间距
  final double? rightSpace;

  /// 设置左右间距
  final double? leftAndRightSpace;

  /// 设置上间距
  final double? topPadding;

  /// 长按回调
  final void Function(int index, String url)? onLongPress;
  const ImageShowTool({
    super.key,
    required this.imgData,
    required this.thumbData,
    this.leftAndRightSpace,
    this.topPadding,
    this.leftSpace,
    this.rightSpace,
    this.onLongPress,
  });

  @override
  Widget build(BuildContext context) {
    var kScreenWidth = MediaQuery.of(context).size.width;

    final lp = leftSpace ?? leftAndRightSpace ?? 10;
    final rp = rightSpace ?? leftAndRightSpace ?? 10;

    var ninePictureW = (kScreenWidth - space * 2 - 2 * itemSpace - (lp + rp));

    var itemWH = ninePictureW / 3;
    int columnCount = imgData!.length > 6
        ? 3
        : imgData!.length <= 3
            ? 1
            : 2;

    return SizedBox(
        height: columnCount * itemWH +
            space * 2 +
            (columnCount - 1) * itemSpace +
            (topPadding != null ? topPadding! : 0),
        child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              // 可以直接指定每行（列）显示多少个Item
              // 一行的Widget数量
              crossAxisCount: 3,
              crossAxisSpacing: itemSpace, // 水平间距
              mainAxisSpacing: itemSpace, // 垂直间距
              childAspectRatio: 1.0, // 子Widget宽高比例
            ),
            physics: const NeverScrollableScrollPhysics(), // 禁止图片列表滚动（会与列表冲突）
            padding: EdgeInsets.only(
                left: lp,
                right: rp,
                top: topPadding ?? 0), //EdgeInsets.all(space), // GridView内边距
            itemCount: imgData!.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                child: ConstrainedBox(
                  constraints: const BoxConstraints.expand(),
                  child: Container(
                    color: Colors.grey[200],
                    child: CachedNetworkImage(
                      imageUrl: thumbData![index],
                      // 显示默认图
                      // placeholder: (context, url) =>  Image.asset('name'),// CircularProgressIndicator(),
                      // 加载失败时显示失败logo
                      errorWidget: (context, url, error) => const Icon(
                        Icons.broken_image_rounded,
                        color: Colors.white,
                        size: 50,
                      ),

                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                onTap: () {
                  debugPrint("点击查看大图 $index");
                  // FadeRoute是自定义的切换过度动画（渐隐渐现） 如果不需要 可以使用默认的MaterialPageRoute
                  Navigator.of(context).push(FadeRoute(
                      page: ImagePreview(
                    imgDataArr: imgData ?? [],
                    thumbDataArr: thumbData ?? [],
                    index: index,
                    onLongPress: onLongPress,
                  )));
                },
              );
            }));
  }
}
